﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using Dokan;

namespace MirrorDrive
{
    public class Logger
    {
        public static bool EnableDisplayCall = false;
        public static bool EnableError = true;
        public static bool EnableInfo = true;

        private static object syncObject = new object();

        public static void Info(string txt, params object[] args)
        {
            if (!EnableInfo)
                return;

            lock (syncObject)
            {

                try
                {
                    txt = string.Format(txt, args);
                }
                catch (FormatException) { }

                txt = "[" + DateTime.Now.ToLongTimeString() + "] " + txt;

                File.AppendAllText("logger.log", txt + Environment.NewLine);

                Console.WriteLine(txt);
            }
        }

        public static int Error(Exception ex)
        {
            int ret = ExceptionHelper.GetReturnCode(ex);
            if (!EnableError)
                return ret;

            StackTrace stackTrace = new StackTrace();
            Logger.Info("{0}: Exception: {1}, Return code: " + ret, stackTrace.GetFrame(1).GetMethod().Name, ex.GetType().Name);
            return ret;
        }

        public static int Error(int ret)
        {
            if (!EnableError)
                return ret;

            StackTrace stackTrace = new StackTrace();
            Logger.Info("{0}: Exception: -, Return code: " + ret, stackTrace.GetFrame(1).GetMethod().Name);
            return ret;
        }

        public static void DisplayCall(string filename, DokanFileInfo info, string root)
        {
            if (!EnableDisplayCall)
                return;

            string path = root + filename;            
            string proc = "";
            int procId = 0;
            try
            {
                procId = (int)info.ProcessId;
                proc = Process.GetProcessById(procId).ProcessName;
            }
            catch { }

            StackTrace stackTrace = new StackTrace();
            Logger.Info(stackTrace.GetFrame(1).GetMethod().Name + ": {0}, process: {2} ({3})", path, proc, procId);
        }
    }
}
